const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl:'',
    userInfo:{
      nickName:'我的昵称',
      avatarUrl:'/images/userPic.png',
      userType:'正式会员',
      account:'',
      password:''
    },
    fileID:'',
    flag:false,
  },

  /**
   * 更换头像，提交后头像再传输到云端
  */
  chooseImage(){
    wx.chooseImage({
      count: 1,
    }).then(res=>{
      let tempFilePaths = res.tempFilePaths[0]
      this.setData({
        avatarUrl:tempFilePaths
      })
    }    
    )
  },
  /**
   * 上传图像到云端
  */
  // uploadImage(tempFilePaths){
  //   wx.cloud.uploadFile({
  //     cloudPath:'userPic/'+Date.now()+'.png',
  //     filePath:tempFilePaths,
  //   }).then(res=>{
  //     let fileId = res.fileID
  //   })
  // },

  /**
   * 提交用户信息
   */
  formSubmit(res){
    let {account,nickName,password,password2} = res.detail.value
    new Promise((resolve,reject)=>{
      let flag = this.check(account,nickName,password,password2)
      if(flag){
        resolve()
      }
    }).then(()=>{
      this.uploadUserInfo(res.detail.value,this.data.avatarUrl) 
    })
  },

  /**
   * 验证账号有效性
   */
  check(account,nickName,password,password2){
    if((this.data.avatarUrl).length == 0){
      wx.showToast({
        title: '头像未添加',
        icon:'error'
      })
      return false
    }else if((account.length == 0) || (nickName.length == 0) || (password2.length == 0) || (password.length == 0)) {
      wx.showToast({
        title: '输入不能为空',
        icon:'error'
      })
      return false
    }else if(password != password2){
      wx.showToast({
        title: '确认密码错误',
        icon:'error'
      })
      return false
    }else{
      wx.showLoading({
        title: '上传中',
      })
      return true
    }

  },

  /**
   * 上传用户信息到数据库
   */
  uploadUserInfo(userInfo,tempFilePaths){
    let olduserInfo = this.data.userInfo
    let newuserInfo = {...olduserInfo,...userInfo}
    // console.log(newuserInfo)
    let {account,nickName,password,userType} = newuserInfo
    wx.cloud.uploadFile({
      cloudPath:'userPic/'+Date.now()+'.png',
      filePath:tempFilePaths,
    }).then(res=>{
      let fileId = res.fileID
      db.collection('userList').add({
        data:{
          account:account,
          nickName:nickName,
          password:password,
          userType:userType,
          avatarUrl:fileId,
          balance:0
        }
      }).then(()=>{
        wx.hideLoading({
        })
        wx.navigateTo({
          url: '/pages/accountLogin/accountLogin',
        })   
      })
    })
  }
})